/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testing.jee.web.view;

import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.AbstractSelect.Filtering;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import testing.jee.ejb.RequestBean;
import testing.jee.entity.User;

/**
 *
 * @author nova
 */
@Component
@Scope(value="session")
public class UserSelectorView extends HorizontalLayout {

    private User currentUser;
    @Autowired
    RequestBean req;
    ComboBox userSelect = new ComboBox("Display user");
    private ValueChangeListener externalListener;
    
    @PostConstruct
    public void init() {
        this.setSpacing(true);
        
        userSelect.setWidth(200, UNITS_PIXELS);
        userSelect.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH);
        userSelect.setNullSelectionAllowed(false);
        userSelect.setImmediate(true);
        userSelect.addListener(new Property.ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                String newValue = (String)event.getProperty().getValue();
                if (newValue != null && !newValue.isEmpty()){
                    User user = req.findUser(newValue);
                    currentUser = user;
                    userSelect.setInputPrompt(currentUser.getId());
                    if (externalListener != null)
                        externalListener.valueChange(event);
                }
            }
        });
        userSelect.setStyleName("wurstkopf");
        addComponent(userSelect);
        initUserSelect();
        if (currentUser == null && !userSelect.getItemIds().isEmpty())
        {
            userSelect.select(userSelect.getItemIds().iterator().next());
            userSelect.setInputPrompt(currentUser.getId());
        }
    }
    
    public void update() {
        initUserSelect();
    }
    
    private void initUserSelect () {
        userSelect.removeAllItems();
        List<User> users = req.listUsers();
        for(User u : users) {
            userSelect.addItem(u.getId());
        }
        if(currentUser != null)
            userSelect.setInputPrompt(currentUser.getId());
    }
    
    public User getCurrentUser() {
        return currentUser;
    }

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }

    public void addListener(ValueChangeListener listener) {
        this.externalListener = listener;
    }
}
